<template>
  <div class="notification-center">
    <el-badge
      :value="unreadCount"
      :max="99"
      :hidden="unreadCount === 0"
      :type="hasUrgentNotification ? 'danger' : 'primary'"
    >
      <el-popover
        placement="bottom-end"
        :width="380"
        trigger="click"
        v-model:visible="popoverVisible"
        :popper-class="[
          'notification-popper',
          { 'has-unread': unreadCount > 0 },
        ]"
      >
        <template #reference>
          <svg-icon icon-class="bell" />
        </template>

        <div class="notification-header">
          <span class="title">消息中心</span>
          <div class="actions">
            <el-tooltip content="全部已读" placement="top">
              <el-button
                link
                size="small"
                :disabled="unreadCount === 0"
                @click="markAllAsRead"
              >
                <el-icon><CircleCheck /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="刷新" placement="top">
              <el-button link size="small" @click="refreshNotifications">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </div>

        <el-tabs v-model="activeTab" stretch>
          <el-tab-pane label="未读" name="unread" lazy>
            <NotificationList
              :data="sortedUnreadNotifications"
              :loading="loading"
              @read="handleMarkRead"
            />
            <div class="load-more" v-if="hasMoreUnread">
              <el-button
                link
                :loading="loadingMore"
                @click="loadMoreNotifications"
              >
                加载更多
              </el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="全部" name="all" lazy>
            <NotificationList
              :data="sortedAllNotifications"
              :loading="loading"
              @read="handleMarkRead"
            />
            <div class="load-more" v-if="hasMoreAll">
              <el-button
                link
                :loading="loadingMore"
                @click="loadMoreNotifications"
              >
                加载更多
              </el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-popover>
    </el-badge>
  </div>
</template>

<script setup>
import { CircleCheck, Refresh } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { websocketService } from "@/services/notification.ws";
import {
  getNotifications,
  markAsRead,
  markAllAsRead as apiMarkAllAsRead,
  getUnreadCount,
} from "@/api/sys/user/notification";

import NotificationList from "./components/NotificationList";

// 状态管理
const activeTab = ref("unread");
const popoverVisible = ref(false);
const notifications = ref([]);
const loading = ref(false);
const loadingMore = ref(false);
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0,
});

// 计算属性
const unreadCount = computed(
  () => notifications.value.filter((n) => !n.is_read).length
);
const hasUrgentNotification = computed(() =>
  notifications.value.some((n) => !n.is_read && n.priority === "urgent")
);

const sortedUnreadNotifications = computed(() =>
  [...notifications.value]
    .filter((n) => !n.is_read)
    .sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
);

const sortedAllNotifications = computed(() =>
  [...notifications.value].sort(
    (a, b) => new Date(b.created_at) - new Date(a.created_at)
  )
);

const hasMoreUnread = computed(
  () => sortedUnreadNotifications.value.length < pagination.value.total
);

const hasMoreAll = computed(
  () => sortedAllNotifications.value.length < pagination.value.total
);

// 方法
const fetchNotifications = async (reset = false) => {
  if (reset) {
    pagination.value.page = 1;
    notifications.value = [];
  }

  try {
    loading.value = true;
    const params = {
      page: pagination.value.page,
      page_size: pagination.value.pageSize,
    };

    const res = await getNotifications(params);
    notifications.value = reset
      ? res.data
      : [...notifications.value, ...res.data];

    pagination.value.total = res.total;
  } catch (error) {
    ElMessage.error(" 获取通知失败: " + error.message);
  } finally {
    loading.value = false;
  }
};

const loadMoreNotifications = async () => {
  if (loadingMore.value) return;

  try {
    loadingMore.value = true;
    pagination.value.page += 1;
    await fetchNotifications(false);
  } finally {
    loadingMore.value = false;
  }
};

const handleMarkRead = async (id) => {
  try {
    await markAsRead(id);
    notifications.value = notifications.value.map((n) =>
      n.id === id ? { ...n, is_read: true } : n
    );
    // 更新未读计数
    const countRes = await getUnreadCount();
    pagination.value.total = countRes.total;
  } catch (error) {
    ElMessage.error(" 标记已读失败: " + error.message);
  }
};

const markAllAsRead = async () => {
  try {
    await apiMarkAllAsRead();
    notifications.value = notifications.value.map((n) => ({
      ...n,
      is_read: true,
    }));
    // 更新未读计数
    const countRes = await getUnreadCount();
    pagination.value.total = countRes.total;
    ElMessage.success(" 全部标记为已读");
  } catch (error) {
    ElMessage.error(" 操作失败: " + error.message);
  }
};

const refreshNotifications = async () => {
  await fetchNotifications(true);
};

// const closePopover = () => {
//   popoverVisible.value = false;
// };

// 生命周期
onMounted(async () => {
  await fetchNotifications();

  // WebSocket 消息处理
  websocketService.addMessageHandler((data) => {
    if (data.event === "new_notification") {
      notifications.value.unshift(data.notification);
      pagination.value.total += 1;

      // 如果当前弹出层未打开，显示桌面通知
      if (!popoverVisible.value && Notification.permission === "granted") {
        new Notification(data.notification.title, {
          body: data.notification.content,
          icon: data.notification.avatar,
        });
      }
    }
  });

  websocketService.init();
});

onUnmounted(() => {
  websocketService.removeMessageHandler();
});
</script>

<style lang="scss" scoped>
.notification-center {
  margin-right: 15px;
  cursor: pointer;

  .notification-icon {
    font-size: 20px;
    transition: transform 0.3s;

    &.has-unread {
      animation: bell-ring 0.5s ease-in-out;
    }
  }

  &:hover .notification-icon {
    transform: scale(1.1);
  }
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid var(--el-border-color-light);

  .title {
    font-weight: bold;
    font-size: 16px;
  }

  .actions {
    display: flex;
    gap: 5px;
  }
}

.load-more {
  text-align: center;
  padding: 10px;
  border-top: 1px solid var(--el-border-color-light);
}

@keyframes bell-ring {
  0% {
    transform: rotate(0deg);
  }
  25% {
    transform: rotate(15deg);
  }
  50% {
    transform: rotate(-15deg);
  }
  75% {
    transform: rotate(15deg);
  }
  100% {
    transform: rotate(0deg);
  }
}
</style>
